package com.tz;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by Administrator on 2016/7/25.
 */
@Configuration
@ComponentScan("com.tz")
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class WebAppConfig {

    //配置DataSource
    @Bean
    public DataSource getDataSource(){
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName("org.h2.Driver");
        bds.setUrl("jdbc:h2:tcp://localhost/~/test");
        bds.setUsername("sa");
        bds.setPassword("");
        return bds;
    }
    //配置SessionFactory
    @Bean
    public LocalSessionFactoryBean getLocalSessionFactoryBean(){
        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
        //1.设置链接
        lsfb.setDataSource(getDataSource());
        //2.设置属性
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect");
        properties.setProperty("hibernate.show_sql","true");
        lsfb.setHibernateProperties(properties);
        //3.设置类
        lsfb.setPackagesToScan("com.tz.entity");

        return lsfb;
    }
    //配置TX
    @Bean
    public HibernateTransactionManager getHibernateTransactionManager(SessionFactory sessionFactory){
        HibernateTransactionManager htm  = new HibernateTransactionManager(sessionFactory);
        return htm;
    }
}
